package com.zzy.emo;

import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.google.common.collect.Maps;
import com.microsoft.playwright.APIRequest;
import com.microsoft.playwright.APIRequestContext;
import com.microsoft.playwright.APIResponse;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.options.ColorScheme;
import com.microsoft.playwright.options.RequestOptions;

public class PlaywrightUtil {

    public static String SMOW_STOCK_URI = "https://stock.xueqiu.com/v5/stock/realtime/quotec.json?symbol=sh000001";


    public static Playwright createPlaywright() {
        Playwright playwright = null;
        try {
            Map<String, String> map = buildEnvMap();
            playwright = Playwright.create(new Playwright.CreateOptions().setEnv(map));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return playwright;
    }

    private static Map<String, String> buildEnvMap() {
        Map<String, String> map = new HashMap<String, String>();
        // 跳过下载浏览器，因为公司是内网，这个配置很重要
        map.put("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "0");
        map.put("PLAYWRIGHT_BROWSERS_PATH", "/home/live-clue-manager/pw-browsers/ms-playwright");
        return map;
    }


    public static Browser createBrowser(Playwright playwright) {
        Browser browser = createBrowser(playwright, false);
        return browser;
    }


    public static Browser createBrowser(Playwright playwright, boolean openWindow) {
        Browser browser = null;
        try {
            browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(!openWindow) // 取消无头模式，我们才能看见浏览器操作
                    .setChromiumSandbox(true).setSlowMo(100) // 减慢执行速度，以免太快
                    .setDevtools(false)); // 打开浏览器开发者工具，默认不打开

        } catch (Exception e) {
            e.printStackTrace();
        }
        return browser;
    }

    public static void closeDriver(Playwright playwright, Browser browser, BrowserContext browserContext) {
        if (null != browserContext) {
            browserContext.close();
        }
        if (null != browser) {
            browser.close();
        }
        if (null != playwright) {
            playwright.close();
        }
    }

    public static String get(String url) {
        String html = PlaywrightUtil.get(url, false);
        return html;
    }

    public static String get(String url, boolean openWindow) {
        Playwright playwright = null;
        Browser browser = null;
        String content = null;
        try {
            Map<String, String> map = buildEnvMap();
            playwright = Playwright.create(new Playwright.CreateOptions().setEnv(map));
            browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(!openWindow) // 取消无头模式，我们才能看见浏览器操作
                    .setSlowMo(1000) // 减慢执行速度，以免太快
                    .setDevtools(true));
            BrowserContext browserContext = browser.newContext(new Browser.NewContextOptions().setColorScheme(ColorScheme.DARK) // 设置浏览器主题，chromium设置了dark好像没用
                    .setViewportSize(100, 100) // 设置浏览器打开后窗口大小
            );
            Page page = browserContext.newPage();
            page.navigate(url);

            content = page.content();

            //content = PuppeteerBrowserUtil.getPageHtml(url);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (browser != null) {
                browser.close();
                browser = null;
            }
            if (playwright != null) {
                playwright.close();
                playwright = null;
            }
        }
        return content;
    }


    public static String getJson(String url) {
        String json = "";
        String content = PlaywrightUtil.get(url, false);
        if (null != content) {
            Document doc = Jsoup.parse(content);
            json = doc.text();
        }
        return json;
    }

    public static String getJson(String url, boolean openWindow) {
        String json = "";
        String content = PlaywrightUtil.get(url, openWindow);
        if (null != content) {
            Document doc = Jsoup.parse(content);
            json = doc.text();
        }
        return json;
    }


    public static String post(String url) {
        String result = PlaywrightUtil.postJson(url, null, null);
        return result;
    }


    public static String postJson(String url, String jsonParam, Map<String, String> headers) {
        String result = "";
        Playwright playwright = null;
        APIRequestContext request = null;
        try {
            String baseUrl = URLUtil.getBaseUrl(url);
            String path = URLUtil.getPath(url);

            Map<String, String> map = buildEnvMap();
            playwright = Playwright.create(new Playwright.CreateOptions().setEnv(map));

            if (null == headers) {
                headers = Maps.newHashMap();
            }
            headers.put("Content-Type", "application/json");
            request = playwright.request().newContext(new APIRequest.NewContextOptions().setBaseURL(baseUrl).setExtraHTTPHeaders(headers));

            RequestOptions option = RequestOptions.create();
            if (null != jsonParam) {
                option.setData(jsonParam);
            }
            APIResponse postAPIResponse = request.post(path, option);
            result = postAPIResponse.text();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (request != null) {
                request.dispose();
                request = null;
            }
            if (playwright != null) {
                playwright.close();
                playwright = null;
            }
        }
        return result;

    }

    public static String post(String url, Map<String, String> paramData, Map<String, String> headers) {
        String result = "";
        Playwright playwright = null;
        APIRequestContext request = null;
        try {
            String baseUrl = URLUtil.getBaseUrl(url);
            String path = URLUtil.getPath(url);


            playwright = Playwright.create();
            headers.put("Content-Type", "application/json");
            request = playwright.request().newContext(new APIRequest.NewContextOptions().setBaseURL(baseUrl).setExtraHTTPHeaders(headers));

            RequestOptions option = RequestOptions.create();
            if (null != paramData) {
                option.setData(paramData);
            }

            APIResponse postAPIResponse = request.post(path, option);
            result = postAPIResponse.text();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (request != null) {
                request.dispose();
                request = null;
            }
            if (playwright != null) {
                playwright.close();
                playwright = null;
            }
        }
        return result;
    }


    public static void main(String[] args) throws MalformedURLException {
        String url = "https://emappdata.eastmoney.com/stockrank/getAllCurrentList";
        String body = PlaywrightUtil.getJson(url);
        System.out.println("----body----" + body);
    }


}
